package com.example.permission.controller;

import com.example.permission.entity.Permission;
import com.example.permission.entity.Role;
import com.example.permission.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询所有全权限
     * @param map
     * @return
     */
    @GetMapping("/per")
    public String perAll(ModelMap map){
        List<Permission> all =  permissionService.findAll();
        map.put("permissions",all);
        return "/permission/permissions";
    }

    /**
     * 跳转到添加页面
     * @return
     */
    @GetMapping("/perm")
    public String add(){
        return "/permission/permissionAdd";
    }

    /**
     * 添加方法
     * @param map
     * @param permission
     * @return
     */
    @PostMapping("/perm")
    public String toAdd(ModelMap map, Permission permission){
        Integer add = permissionService.add(permission);
        map.put("add",add);
        List<Permission> all = permissionService.findAll();
        map.put("permissions",all);
        return "/permission/permissions";
    }

    /**
     * 跳转到修改页面
     * @param id
     * @param map
     * @return
     */
    @GetMapping("/per/{id}")
    public String update(@PathVariable Integer id, ModelMap map){
        Permission idAll = permissionService.getIdAll(id);
        map.put("permissions",idAll);
        return "/permission/permissionAdd";
    }

    /**
     * 修改方法
     * @param permission
     * @param map
     * @return
     */
    @PutMapping("/perm")
    public String toUpdate(Permission permission, ModelMap map){
        permissionService.update(permission);
        List<Permission> all = permissionService.findAll();
        map.put("permissions",all);
        return "/permission/permissions";
    }

    /**
     * 删除方法
     * @param id
     * @param map
     * @return
     */
    @DeleteMapping("/per/{id}")
    public String delete(@PathVariable Integer id, ModelMap map){
        permissionService.delete(id);
        List<Permission> all = permissionService.findAll();
        map.put("permissions",all);
        return "/permission/permissions";
    }
    @GetMapping("/pers/{ids}")
    public String del(ModelMap map,@PathVariable String ids){
        String[] split = ids.split(",");
        for (String i: split) {
            permissionService.delete(Integer.parseInt(i));
        }
        List<Permission> all = permissionService.findAll();
        map.put("permissions",all);
        return "/permission/permissions";
    }
}
